package leetcode100;

public class lc030 {
    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;

        ListNode res = new lc030().removeNthFromEnd(node1,4);
        res.visit();

    }

    public ListNode removeNthFromEnd(ListNode head, int n) {

        int count=0;
        ListNode cur = head;
        while(cur!=null) {
            cur = cur.next;
            count++;
        }

        if (count==n) {
            return head.next;
        }

        int step = count-n;
        cur = head;
        for (int i = 0; i < step-1; i++) {
            cur = cur.next;
        }
        
        ListNode pre = cur;
        cur = cur.next;
        pre.next = cur.next;
        return head;

    }
}
